# -*- encoding: utf-8 -*-
"""
@Project : AIGateWay 
@FileName: async_handler
@Time    : 2020/11/26 14:59
@Author  : chenych
@Desc    :
"""

import json
from Dao.t_log_dao import insert_log
from Core import mysql_log_loop
import datetime
from Business.SmartHome.face_delet_task import FaceDeletTask

from Core import SYS_CODE,conf
import ailog

from pydantic import BaseModel
import time
from Core import NODE

class FaceDeletItem(BaseModel):
    uid: str = None
    deviceId: str = None
    seqid: str = None
    timestamp: str = None
    visitorId: str = None






class FaceDeletHandle():

    name = 'FaceDelet'

    @classmethod
    def response_error(cls, seqid, code, message=''):
        res = {}
        res['seqid'] = seqid
        res['code'] = code
        res['message'] = message

        #res = json.dumps(res, ensure_ascii=False)
        return res

    @classmethod
    def response_res(cls, res):
        ailog.info('result : {}'.format(res))

        #res = json.dumps(res, ensure_ascii=False)
        return res

    @classmethod
    def check_args(cls,req_item):

        args_dict = {}
        args_list = {
                    'uid': True,
                    'timestamp': True,
                    'seqid': True,
                    'deviceId': True,
                    'visitorId': False
                    }

        for k, v in args_list.items():
            if v:
                val = getattr(req_item,k,None)
                if val is None:
                    cls.response_error(getattr(req_item,'seqid',''),
                                        SYS_CODE.RESPCODE.KEYERROR,
                                      '服务必填参数[%s]缺失或未填写'%(k)
                        )
                    return None
                else:
                    args_dict[k] = val
            else:
                args_dict[k] = getattr(req_item,k,None)

        return args_dict


    @classmethod
    async def post(cls,item:FaceDeletItem):

        try:

            start_time = time.time()
            args_dict = {}
            args_dict = cls.check_args(item)
            if args_dict is None:
                post_data = str(item)
                ailog.warning('#error post_data: {}'.format(post_data))
                return cls.response_error(getattr(item,'seqid',''),
                                        SYS_CODE.RESPCODE.KEYERROR,
                                      '服务必填参数缺失或未填写'
                        )


            res = await FaceDeletTask.run(args_dict)

            end_time = time.time()

            ailog.info("done : {}".format(end_time-start_time))

            try:

                mysql_log_loop.run(insert_log(ip='',
                                              url='',
                                              seqid=args_dict.get('seqid', ''),
                                              method=cls.name,
                                              args=json.dumps(args_dict,ensure_ascii=False),
                                              output=json.dumps(res,ensure_ascii=False),                                              
                                              code=res.get('code',''),
                                              use_time=end_time-start_time,
                                              create_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                              node=NODE))
            except Exception as e:
                print('log error : {}'.format(e))


            return  cls.response_res(res)



        except Exception as e:

            ailog.error(e)


            mysql_log_loop.run(insert_log(ip='',
                                          url='',
                                          seqid=args_dict.get('seqid', ''),
                                          method=cls.name,
                                          args=str(item),
                                          output='error : {}'.format(e),
                                          code=SYS_CODE.RESPCODE.FAIL,
                                          use_time=0,
                                          create_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                          node=NODE))

            return  cls.response_error(args_dict.get('seqid', ''),
                               SYS_CODE.RESPCODE.FAIL,
                               SYS_CODE.RESPCODE.get_msg(SYS_CODE.RESPCODE.FAIL))
